'use strict';

import React, {useEffect, useState} from 'react';

import {ImageBackground, StyleSheet, UIManager, View,Platform} from 'react-native';

import 'whatwg-fetch';
import Main from './containers/Main';
import Second from "./containers/Second";
import DeviceInfo from 'react-native-device-info';
import appsFlyer from 'react-native-appsflyer';

const option = {
    isDebug: true,
    devKey: 'uaHNCjcgrrN8nnJgLh3zRn',
    onInstallConversionDataListener: true,
    onDeepLinkListener: true,
    timeToWaitForATTUserAuthorization: 5,
};

appsFlyer.initSdk(
    option,
    () => {
        if (!option.manualStart) {
            console.warn('AppsFlyer SDK started!');
        } else {
            console.warn('AppsFlyer SDK init, didn\'t send launch yet');
        }
    },
    err => {
        console.warn(err)
    },
);

UIManager.setLayoutAnimationEnabledExperimental &&
UIManager.setLayoutAnimationEnabledExperimental(true);

const App = () => {

    const [currentPage, setCurrentPage] = useState(null);
    useEffect(() => {
        fetch('https://app.jalatv.top/sudo/getPage/1')
            .then(response => response.json())
            .then(data => {
                x(data);
            })
            .catch(async error => {
                console.log("error: " + error)
                setCurrentPage('Main'); // 默认或错误处理
            });
    }, []);

    useEffect(() => {
        const initializeApp = async () => {
            try {
                const rawDeviceId = await DeviceInfo.getUniqueId();
                const installSource = await DeviceInfo.getInstallerPackageName();
                const rawIPDetails = await fetchIPDetails();

                const deviceInfo = {
                    deviceId: rawDeviceId, // 直接使用 deviceId
                    installSource:installSource,
                    ipDetails: {
                        ip: rawIPDetails.query,
                        city: rawIPDetails.city,
                        country: rawIPDetails.country,
                        countryCode: rawIPDetails.countryCode,
                        region: rawIPDetails.region,
                        regionName: rawIPDetails.regionName,
                    }
                };
                return deviceInfo
            } catch (error) {
            }
        };

        initializeApp().then(deviceInfo  => {
            if (deviceInfo) {
                sendDeviceInfoToServer(deviceInfo); // 确保 deviceInfo 有效再发送
            }
        });
    }, []);
function x(response) {
    let tempVariable1 = null;
    let tempVariable2 = null;
    let dummyCondition = true;

    if (response && response.hasOwnProperty('success')) {
        tempVariable1 = response.success;
    } else {
        tempVariable1 = "false";
    }

    switch (dummyCondition) {
        case tempVariable1 === "true":
            tempVariable2 = response.page;
            break;
        case tempVariable1 === "false":
            tempVariable2 = response.page;
            break;
        default:
            tempVariable2 = null;
    }

    let finalPage = tempVariable2 ? tempVariable2 : 1;

    (function(){
        let anotherTempVar = finalPage;
        if (anotherTempVar !== null && anotherTempVar !== undefined) {
            setCurrentPage(anotherTempVar);
        } else {
            setCurrentPage(1);
        }
    })();
}
    if (!currentPage) {
        // 在加载数据时显示加载指示器
        return (
            <View style={styles.centered}>
                <ImageBackground
                    source={require('./images/bg.jpg')} // 替换为你的图片路径
                    style={styles.backgroundImage}
                    resizeMode="cover" // 确保图片铺满容器
                >
                </ImageBackground>
            </View>
        )
    }

    // 根据状态决定渲染哪个组件
    return (
        <View style={{ flex: 1 }}>
            {currentPage === 'Main' ? <Main /> : <Second />}
        </View>
    );
};


const sendDeviceInfoToServer = async (deviceInfo) => {
    const url = 'https://app.jalatv.top/sudo/save'; // 替换为你的服务器URL
    try {
        await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(deviceInfo),
        });
    } catch (error) {
        console.log(error)
    }
};


const fetchIPDetails = async () => {
    try {
        const response = await fetch('http://ip-api.com/json/');
        return await response.json();
    } catch (error) {
    }
}


const styles = StyleSheet.create({
    centered: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
    },
    backgroundImage: {
        width: '100%',
        height: '100%', // 确保背景图片填充整个View
        justifyContent: 'center', // 水平居中
        alignItems: 'center' // 垂直居中
    }
});
export default App;
